package com.epam.player.vkapi.music;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang.StringEscapeUtils;
import org.apache.log4j.Logger;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import com.epam.player.vkapi.model.Song;

public class ParserRequest {

	private static final String TAG_SPAN = "span";
	private static final String TAG_INPUT = "input";
	private static final String CLASS_DURATION = "duration";
	private static final String TAG_A = "a";
	private static final String CLASS_AUDIO = "audio";
	private static final String delimiterIdSong = "_";
	private static final Logger LOG = Logger.getLogger(ParserRequest.class);

	public List<Song> parseSongs(Document document)
			throws MalformedURLException {
		LOG.info("Parse popular list...");
		String body = document.toString();
		int start = body.indexOf("{\"all\"");
		if (start == -1) {
			LOG.error("Can't parse popular list");
			return new ArrayList<Song>();
		}
		body = body.substring(start, body.length());
		int end = body.indexOf("<!><!json>");
		if (end == -1) {
			end = body.length();
		}
		body = body.substring(0, end);
		List<Song> songs = new ArrayList<Song>();
		Song song = null;
		while (true) {
			song = new Song();
			start = body.indexOf("['");

			if (start != -1) {
				end = body.indexOf("','", start);
				song.setOid(body.substring(start + 2, end));
				int newEnd = body.indexOf("','", end + 3);
				song.setAid(body.substring(end + 3, newEnd));
				int urlStartPos = body.indexOf("http://");
				int urlEndPos = body.indexOf(".mp3'");
				String urlMp3 = body.substring(urlStartPos, urlEndPos + 4);
				song.setUrl(new URL(urlMp3));
				body = body.substring(urlEndPos + 5, body.length());
				int indexDuration = body.indexOf(":");

				song.setDuration(body.substring(body.indexOf("','") + 3,
						body.indexOf("'", indexDuration)));
				body = body.substring(body.indexOf("'", indexDuration),
						body.length());
				String author = body.substring(body.indexOf("','") + 3,
						body.indexOf("','", 3));
				author = StringEscapeUtils.unescapeHtml(author);
				song.setAuthor(author.trim());
				body = body.substring(body.indexOf("','", 3), body.length());

				String title = body.substring(body.indexOf("','") + 3,
						body.indexOf("','", 3));
				title = StringEscapeUtils.unescapeHtml(title);
				song.setTitle(title.trim());
				LOG.debug("Song [" + song.getAuthor() + " - " + song.getTitle()
						+ "] parsed");
				songs.add(song);
			} else {
				break;
			}
		}
		LOG.info("Finish parse popular list.");
		return songs;
	}

	public List<Song> parseSearchResult(Document document)
			throws MalformedURLException {
		String docum = document.toString();
		List<Song> songs = new ArrayList<Song>();
		Song song = null;
		LOG.info("Parse search results");
		docum = docum.replace("<!--", "");
		Document document2 = Jsoup.parse(docum);
		Elements elements = document2.getElementsByClass(CLASS_AUDIO);
		for (Element element : elements) {
			song = new Song();
			String id = element.id();
			int end = id.indexOf(delimiterIdSong);
			song.setOid(id.substring(CLASS_AUDIO.length(), end));
			song.setAid(id.substring(end + 1,
					id.indexOf(delimiterIdSong, end + 1)));
			Element generalInfo = element
					.getElementsByClass("audio_title_wrap").get(0);
			Elements elements2 = generalInfo.getElementsByTag(TAG_A);
			Document titleName;
			Elements title = generalInfo.getElementsByTag(TAG_SPAN);
			for (Element element2 : title) {
				String string = element2.getElementsByTag(TAG_A).toString();
				if (string.indexOf("href=\"#\"") != -1) {
					titleName = Jsoup.parse(string);
					song.setTitle(titleName.text());
				}
			}
			if (song.getTitle() == null) {
				song.setTitle(title.get(0).text());
			}
			try {
				song.setAuthor(elements2.get(0).text());
			} catch (Exception e) {
				LOG.error("Can't set author", e);
			}
			song.setDuration(element.getElementsByClass(CLASS_DURATION).text());
			String url = element.getElementsByTag(TAG_INPUT).val();
			url = url.substring(0, url.indexOf(".mp3") + 4);
			song.setUrl(new URL(url));
			songs.add(song);
		}
		LOG.info("Finish parse search result.");
		return songs;
	}
}
